<?php
/**
 * 公共控制器
 * 输出勋章
 * 验证用户身份token
 * @author Edwin
 */

namespace V1\Controller;

use Common\Common\Tools;
use Think\Controller;

class ToolsController extends Controller
{

    /**
     * 短信发送日志
     * @param $mobile
     * @param $code
     * @return false|int
     */
    function sendSmsLogs($mobile, $code)
    {
        $data = ['mobile'=>$mobile,'code'=>$code];
        $result = M('sms_logs')->add($data);
        return $result;
    }

    /**
     * 短信预警
     * @return bool
     */
    function sendSmsWarning($mobile, $content)
    {
        //验证码超过30分钟/100条自动报警
        $num = (int)F('tags') + 1;
        F('tags', $num);
        $count = (int)F('tags');

        if ($count > 100) {
            $edt = time();
            $sdt = F('sdt');
            if (($edt - $sdt) < 3600) {
                $this->putLog('s', "预警");
                F('send', 'ok');
                //18037278716
                inSendSms('18567212018', '短信发送数量预警！');
            } else {
                $this->putLog('s', "清空缓存");
                F('tags', null);
                F('sdt', null);
            }
        } elseif ($count == 1) {
            $this->putLog('s', "统计数量等于1，写入时间戳");
            F('sdt', time());
        }

        $this->sendSmsLogs($mobile, $content);  //短信发送记录
    }

    /**
     * 生成记录信息
     * @param $log_title
     * @param $log_info
     */
    function putLog($log_info, $log_title = 'log')
    {
        $log_dir = APP_ROOT . C('UPLOADS') . "Log/";
        $log_file_name = "app_know_api_log.md";
        Tools::createDir($log_dir);
        $log_path = $log_dir . "/" . $log_file_name;
        $now = date("Y-m-d H:i:s", time());
        $content = "***\r##" . $now . "\r" . $log_title . ":\r\r```php\r" . var_export($log_info, true) . "\r```\r\r";
        file_put_contents($log_path, $content, FILE_APPEND);
    }

    /**
     * send sms mail
     * @param  string $content send message
     * @param  string $sendPhone send phone number
     * @param  int $stop is exit or not
     * @return int status
     */
    function sendSms($content, $sendPhone, $md5 = '', $stop = 0)
    {
        $this->sendSmsWarning($sendPhone, $content);  //短信预警
        if (F('send') != 'ok') {
            $md5code = strtoupper(md5(strtoupper(md5($sendPhone . 'NONG654YIW_ENYAO!@#'))));
            if ($md5 == $md5code) {
                $content = urlencode($content);
                $cnsmsUrl = 'http://api.cnsms.cn/?ac=send&uid=' . C('SMS_UID') . '&pwd=' . md5(C('SMS_PASSWORD')) . '&mobile=' . $sendPhone . '&content=' . $content;
                if ($stop != 0) {
                    exit();
                }
                return file_get_contents($cnsmsUrl);
            } else {
                return false;
            }
        } else {
            return false;
        }
    }
}
